package com.Policing.Facility_Maintenance;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.*;

import com.Policing.BaseActivity;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.R;
import com.Policing.Since_case.Since_case;
import com.hb.dialog.dialog.LoadingDialog;
import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

public class Abnormal_File extends BaseActivity {
    String path ; // 下视频
    private Handler handler = new Handler();
    String path2 ; // 下语音
    private Dialog dialog;

    private List<Bitmap> bitmaps = new ArrayList<>();
    private VideoView videoview;
    private ImageView fh,ImageView_1,ImageView_2,ImageView_3,ImageView_4,ImageView_5;
    private TextView title_text;
    private String url="http://"+ Ip_Set.IP+"/api/deviceMainImageQuery";
    String fileName,maintainId;
    LoadingDialog loadingDialog;
    String fileName2;
    File soundFile;
    private MediaPlayer mPlayer = null;
    private Button  play ;
    @Override
    public int intiLayout() {

        return R.layout.abnormal_file;
    }

    @Override
    public void initView() {

        ImageView_1 = (ImageView) findViewById(R.id.ImageView_1);
        ImageView_2 = (ImageView) findViewById(R.id.ImageView_2);
        ImageView_3 = (ImageView) findViewById(R.id.ImageView_3);
        ImageView_4 = (ImageView) findViewById(R.id.ImageView_4);
        ImageView_5 = (ImageView) findViewById(R.id.ImageView_5);
        ImageView_1.setVisibility(View.GONE);
        ImageView_2.setVisibility(View.GONE);
        ImageView_3.setVisibility(View.GONE);
        ImageView_4.setVisibility(View.GONE);
        ImageView_5.setVisibility(View.GONE);

        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("异常文件");
        fh = (ImageView) findViewById(R.id.fh);
        play = (Button) findViewById(R.id.play);
        videoview = (VideoView) findViewById(R.id.video_view);


    }

    @Override
    public void initData() {
        Intent intent =getIntent();
        path = "http://"+Ip_Set.IP+"/api/deviceMainVideoDownload?maintainId="+intent.getStringExtra("maintainId");
        path2 = "http://"+Ip_Set.IP+"/api/deviceMainVoiceDownload?maintainId="+intent.getStringExtra("maintainId");
        maintainId = intent.getStringExtra("maintainId");
        try{
            // 创建文件夹，在存储卡下
            String dirName = Environment.getExternalStorageDirectory() + "/"+"ISOS";
            File file = new File(dirName);
            // 文件夹不存在时创建
            if (!file.exists()) {
                file.mkdir();
            }
            // 下载后的文件名
            int i = path.lastIndexOf("/"); // 取的最后一个斜杠后的字符串为名
            fileName = dirName + path.substring(i, path.length());
            File file1 = new File(fileName);
            if (file1.exists()) {
                // 如果已经存在, 就不下载了, 去播放
                startVideo(fileName);
            }else {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        DOWNLOAD(path,fileName,"1");
                    }
                }).start();
            }


        }catch (NullPointerException E){
            Log.i("2131213123123","!2312312");
        }

        videoview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (videoview.isPlaying()){
                    videoview.pause();
                }else {
                    videoview.start();
                }

            }
        });
        fh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    data();
                }catch(NullPointerException e){
                    Toast.makeText(Abnormal_File.this,"没有语音！！",Toast.LENGTH_SHORT).show();
                }

                mPlayer = new MediaPlayer();
                try{
                    mPlayer.setDataSource(String.valueOf(soundFile));
                    mPlayer.prepare();
                    mPlayer.start();
                }catch(IOException e){
                   Toast.makeText(Abnormal_File.this,"没有语音！！",Toast.LENGTH_SHORT).show();
                }
            }
        });
        ImageView_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog = new Dialog(Abnormal_File.this,R.style.FullActivity);
                WindowManager.LayoutParams attributes = dialog.getWindow().getAttributes();
                attributes.width = WindowManager.LayoutParams.MATCH_PARENT;
                attributes.height = WindowManager.LayoutParams.MATCH_PARENT;
                dialog.getWindow().setAttributes(attributes);

                /*ImageView_1.setDrawingCacheEnabled(true);
                Bitmap bitmap = Bitmap.createBitmap(ImageView_1.getDrawingCache());
                ImageView_1.setDrawingCacheEnabled(false);*/
                ImageView imageView= new ImageView(Abnormal_File.this);
                imageView.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                imageView.setImageBitmap(bitmaps.get(0));
                dialog.setContentView(imageView);
                //大图的点击事件（点击让他消失）
                dialog.show();
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
            }
        });
        ImageView_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog = new Dialog(Abnormal_File.this,R.style.FullActivity);
                WindowManager.LayoutParams attributes = dialog.getWindow().getAttributes();
                attributes.width = WindowManager.LayoutParams.MATCH_PARENT;
                attributes.height = WindowManager.LayoutParams.MATCH_PARENT;
                dialog.getWindow().setAttributes(attributes);

               /* ImageView_2.setDrawingCacheEnabled(true);
                Bitmap bitmap = Bitmap.createBitmap(ImageView_2.getDrawingCache());
                ImageView_2.setDrawingCacheEnabled(false);*/
                ImageView imageView= new ImageView(Abnormal_File.this);
                imageView.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                imageView.setImageBitmap(bitmaps.get(1));
                dialog.setContentView(imageView);
                //大图的点击事件（点击让他消失）
                dialog.show();
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
            }
        });
        ImageView_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog = new Dialog(Abnormal_File.this,R.style.FullActivity);
                WindowManager.LayoutParams attributes = dialog.getWindow().getAttributes();
                attributes.width = WindowManager.LayoutParams.MATCH_PARENT;
                attributes.height = WindowManager.LayoutParams.MATCH_PARENT;
                dialog.getWindow().setAttributes(attributes);

               /* ImageView_3.setDrawingCacheEnabled(true);
                Bitmap bitmap = Bitmap.createBitmap(ImageView_3.getDrawingCache());
                ImageView_3.setDrawingCacheEnabled(false);*/
                ImageView imageView= new ImageView(Abnormal_File.this);
                imageView.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                imageView.setImageBitmap(bitmaps.get(2));
                dialog.setContentView(imageView);
                //大图的点击事件（点击让他消失）
                dialog.show();
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
            }
        });
        ImageView_4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog = new Dialog(Abnormal_File.this,R.style.FullActivity);
                WindowManager.LayoutParams attributes = dialog.getWindow().getAttributes();
                attributes.width = WindowManager.LayoutParams.MATCH_PARENT;
                attributes.height = WindowManager.LayoutParams.MATCH_PARENT;
                dialog.getWindow().setAttributes(attributes);

               /* ImageView_4.setDrawingCacheEnabled(true);
                Bitmap bitmap = Bitmap.createBitmap(ImageView_4.getDrawingCache());
                ImageView_4.setDrawingCacheEnabled(false);*/
                ImageView imageView= new ImageView(Abnormal_File.this);
                imageView.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                imageView.setImageBitmap(bitmaps.get(3));
                dialog.setContentView(imageView);
                //大图的点击事件（点击让他消失）
                dialog.show();
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
            }
        });
        ImageView_5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog = new Dialog(Abnormal_File.this,R.style.FullActivity);
                WindowManager.LayoutParams attributes = dialog.getWindow().getAttributes();
                attributes.width = WindowManager.LayoutParams.MATCH_PARENT;
                attributes.height = WindowManager.LayoutParams.MATCH_PARENT;
                dialog.getWindow().setAttributes(attributes);

              /*  ImageView_5.setDrawingCacheEnabled(true);
                Bitmap bitmap = Bitmap.createBitmap(ImageView_5.getDrawingCache());
                ImageView_5.setDrawingCacheEnabled(false);*/
                ImageView imageView= new ImageView(Abnormal_File.this);
                imageView.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                imageView.setImageBitmap(bitmaps.get(4));
                dialog.setContentView(imageView);
                //大图的点击事件（点击让他消失）
                dialog.show();
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });

            }
        });
        loadingDialog = new LoadingDialog(this);
        loadingDialog.setMessage("加载中....");
        loadingDialog.show();
        load();

    }

    private void data() {
        // 创建文件夹，在存储卡下
        String dirName = Environment.getExternalStorageDirectory() + "/" + this.getPackageName();
        File file = new File(dirName);
        // 文件夹不存在时创建
        if (!file.exists()) {
            file.mkdir();
        }
        // 下载后的文件名
        int i = path.lastIndexOf("/"); // 取的最后一个斜杠后的字符串为名
        fileName2 = dirName + path.substring(i, path.length());
        soundFile = new File(fileName2);
        new Thread(new Runnable() {
            @Override
            public void run() {
                DOWNLOAD(path2,fileName2,"2");
            }
        }).start();

    }

    // 下载具体操作
    private void DOWNLOAD(String path, final String fileName, String sta) {

        try {
            URL url = new URL(path);
            // 打开连接
            URLConnection conn = url.openConnection();
            // 打开输入流
            InputStream is = conn.getInputStream();
            // 创建字节流
            byte[] bs = new byte[1024];
            int len;
            OutputStream os = new FileOutputStream(fileName);
            // 写数据
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            // 完成后关闭流
            Log.e(TAG, "download-finish");
            os.close();
            is.close();
            if (sta.equals("1")){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        startVideo(fileName);
                    }
                });
            }
            //            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "e.getMessage() --- " + e.getMessage());
        }
    }
    // 播放视频
    private void startVideo(String videoURI) {
        videoview.setVisibility(View.VISIBLE);
       // videoview.setLayoutParams(new RelativeLayout.LayoutParams(UtilsTools.getCurScreenWidth(mContext), UtilsTools.getCurScreenWidth(mContext) / 3 * 4)); // 此行代码是设置视频的宽高比是3/4,不需要就注释掉即可
        // 设置播放加载路径
        //        videoview.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.aaa));
        videoview.setVideoURI(Uri.parse(videoURI));
        // 播放
        videoview.start();

    }
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,dip2px(this,235f));
            params.addRule(RelativeLayout.CENTER_IN_PARENT);
            videoview.setLayoutParams(params);
        } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            videoview.setLayoutParams(new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
        }
    }
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
    private void load() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
                FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
                formBody.add("maintainId",maintainId)
                        .add("source", Since_case.set().getSource());
                //传递键值对参数
                Request request = new Request.Builder()//创建Request 对象。
                        .url(url)
                        .post(formBody.build())//传递请求体
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //回调方法的使用与get异步请求相同
                        Log.i("123123", "error");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String responseData = response.body().string();
                        //回调方法的使用与get异步请求相同
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Log.i("123123", responseData);
                                    JSONObject json = new JSONObject(responseData);
                                    if (json.getString("state").equals("1")){

                                        JSONArray jsonArray = json.getJSONArray("images");
                                        Log.i("123123json", String.valueOf(jsonArray.length()));
                                        for (int i=0;i<jsonArray.length();i++){
                                            byte [] input = Base64.decode(jsonArray.get(i).toString(), Base64.DEFAULT);
                                            Bitmap  bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);

                                            bitmaps.add(bitmap);
                                            if (i==0){
                                                ImageView_1.setVisibility(View.VISIBLE);
                                                ImageView_1.setImageBitmap(bitmap);
                                                Log.i("123123json", String.valueOf(i));
                                            }
                                            if (i==1){
                                                ImageView_2.setVisibility(View.VISIBLE);
                                                ImageView_2.setImageBitmap(bitmap);
                                                Log.i("123123json", String.valueOf(i));
                                            }
                                            if (i==2){
                                                ImageView_3.setVisibility(View.VISIBLE);
                                                ImageView_3.setImageBitmap(bitmap);
                                                Log.i("123123json", String.valueOf(i));
                                            }
                                            if (i==3){
                                                ImageView_4.setVisibility(View.VISIBLE);
                                                ImageView_4.setImageBitmap(bitmap);
                                                Log.i("123123json", String.valueOf(i));
                                            }
                                            if (i==4){
                                                ImageView_5.setVisibility(View.VISIBLE);
                                                ImageView_5.setImageBitmap(bitmap);
                                                Log.i("123123json", String.valueOf(i));
                                            }

                                        }
                                        loadingDialog.dismiss();

                                    }
                                    if (json.getString("state").equals("0")){
                                        loadingDialog.dismiss();
                                        Toast.makeText(Abnormal_File.this,"没有图片",Toast.LENGTH_LONG).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                    }
                });

            }
        }).start();
    }
}
